/*
 * Copyright (C) 2008 ProSyst Software GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modulefusion.featurepack.wicket;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.Servlet;

import org.apache.wicket.protocol.http.WebApplication;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebApplicationTracker extends ServiceTracker {

	private final Logger logger = LoggerFactory.getLogger(WebApplicationTracker.class);

	private final BundleContext context;

	private final Map<ServiceReference, ServiceRegistration> webApplicationServlets = new HashMap<ServiceReference, ServiceRegistration>();

	public WebApplicationTracker(BundleContext context) {
		super(context, WebApplication.class.getName(), null);
		this.context = context;
	}

	@Override
	public Object addingService(ServiceReference reference) {
		WebApplication app = (WebApplication) context.getService(reference);
		if (app != null) {
			BundleContext context = reference.getBundle().getBundleContext();
			Properties p = createPropertiesFromRegistration(reference);

			LocalWicketServlet lws = new LocalWicketServlet(context, app);
			logger.info("Registering Servlet '{}' for WebApplication '{}'", lws, app);
			ServiceRegistration reg = context.registerService(Servlet.class.getName(), lws, p);
			webApplicationServlets.put(reference, reg);
		}
		return super.addingService(reference);
	}

	@Override
	public void removedService(ServiceReference reference, Object service) {
		try {
		webApplicationServlets.get(reference).unregister();
		} catch (IllegalStateException e) {
			// OK
		}
		webApplicationServlets.remove(reference);
		super.remove(reference);
	}

	@Override
	public synchronized void close() {
		for (ServiceRegistration reg : webApplicationServlets.values()) {
			reg.unregister();
		}
		super.close();
	}

	private Properties createPropertiesFromRegistration(ServiceReference reference) {
		Properties p = new Properties();
		String[] keys = reference.getPropertyKeys();
		for (String key : keys) {
			Object value = reference.getProperty(key);
			p.put(key, value);
		}
		return p;
	}

}
